package org.dbstar.scheduler.control.db.job;

import java.sql.Types;
import java.util.Map;

import net.sf.json.JSONSerializer;

import org.dbstar.scheduler.beans.Job;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;


/**
 * Job的Update对象
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-29
 */
public class JobUpdate extends SqlUpdate {
	public JobUpdate(JdbcTemplate jdbcTemplate) {
		super();
		setJdbcTemplate(jdbcTemplate);
		setSql("UPDATE SCHD_JOB SET CONTENT=?, PARAMETER_SIZE=?, PARAMETER_DATA=?, LAUNCH_TIME=?, FINISH_TIME=?, RESULT=?, READY=?, SUCCEED=?, RETRY=?, MAX_RETRY=? WHERE SYSTEM_IDENTIFIER=? AND SEQUENCE=?");
		declareParameter(new SqlParameter("CONTENT", Types.VARCHAR));
		declareParameter(new SqlParameter("PARAMETER_SIZE", Types.INTEGER));
		declareParameter(new SqlParameter("PARAMETER_DATA", Types.VARCHAR));
		declareParameter(new SqlParameter("LAUNCH_TIME", Types.BIGINT));
		declareParameter(new SqlParameter("FINISH_TIME", Types.BIGINT));
		declareParameter(new SqlParameter("RESULT", Types.VARCHAR));
		declareParameter(new SqlParameter("READY", Types.BOOLEAN));
		declareParameter(new SqlParameter("SUCCEED", Types.BOOLEAN));
		declareParameter(new SqlParameter("RETRY", Types.INTEGER));
		declareParameter(new SqlParameter("MAX_RETRY", Types.INTEGER));
		declareParameter(new SqlParameter("SYSTEM_IDENTIFIER", Types.VARCHAR));
		declareParameter(new SqlParameter("SEQUENCE", Types.INTEGER));
	}

	public int updateJob(Job job) {
		int result = update(job.getContent(), job.getParameterSize(), parseParametersJson(job.getParameters()),
				job.getLaunchTime(), job.getFinishTime(), job.getResultString(), job.isReady(), job.isSucceed(),
				job.getRetry(), job.getMaxRetry(), job.getIdentifier().getSystemIdentifier(), job.getIdentifier()
						.getSequence());
		return result;
	}

	private String parseParametersJson(Map<String, String> parameters) {
		if (parameters == null || parameters.isEmpty()) {
			return null;
		} else {
			return JSONSerializer.toJSON(parameters).toString();
		}
	}
}
